package cn.yh.nft.turbo.admin.controller;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.yh.nft.turbo.admin.infrastructure.exception.AdminException;
import cn.yh.nft.turbo.admin.param.AdminLoginParam;
import cn.yh.nft.turbo.admin.vo.AdminLoginVO;
import cn.yh.nft.turbo.api.user.constant.UserRole;
import cn.yh.nft.turbo.api.user.request.UserPageQueryRequest;
import cn.yh.nft.turbo.api.user.request.UserQueryRequest;
import cn.yh.nft.turbo.api.user.response.UserOperatorResponse;
import cn.yh.nft.turbo.api.user.response.UserQueryResponse;
import cn.yh.nft.turbo.api.user.response.data.UserInfo;
import cn.yh.nft.turbo.api.user.service.UserFacadeService;
import cn.yh.nft.turbo.api.user.service.UserManageFacadeService;
import cn.yh.nft.turbo.base.response.PageResponse;
import cn.yh.nft.turbo.base.utils.MoneyUtils;
import cn.yh.nft.turbo.web.util.MultiResultConvertor;
import cn.yh.nft.turbo.web.vo.MultiResult;
import cn.yh.nft.turbo.web.vo.Result;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.hibernate.validator.internal.constraintvalidators.bv.NotNullValidator;
import org.springframework.web.bind.annotation.*;

import static cn.yh.nft.turbo.admin.infrastructure.exception.AdminErrorCode.ADMIN_USER_NOT_EXIST;

/**
 * @ClassName: UserAdminController
 * @Author: 草莓爱上啵啵
 *  用户后台管理
 *
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("admin/user")
@CrossOrigin(origins = "*")
public class UserAdminController {



    @DubboReference(version = "1.0.0")
    private UserFacadeService userFacadeService;

    @DubboReference(version = "1.0.0")
    private UserManageFacadeService userManageFacadeService;

    private static final Integer DEFAULT_LOGIN_SESSION_TIMEOUT = 60 * 60 * 24 * 7 ;


    /**
     * 查询用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result<UserInfo> getUserInfo(){
        String userId = (String) StpUtil.getLoginId();

        UserQueryRequest request = new UserQueryRequest(Long.valueOf(userId));
        UserQueryResponse<UserInfo> response = userFacadeService.query(request);
        UserInfo userInfo = response.getData();

        if (userInfo == null){
            throw new AdminException(ADMIN_USER_NOT_EXIST);
        }
        return Result.success(userInfo);
    }

    /**
     * 分页查询用户列表集合
     *
     * @param state
     * @param keyWord
     * @param pageSize
     * @param currentPage
     * @return
     */
    @GetMapping("/userList")
    public MultiResult<UserInfo> userList(@NotBlank String state, String keyWord, int pageSize, int currentPage){
        UserPageQueryRequest userPageQueryRequest = new UserPageQueryRequest();
        userPageQueryRequest.setState(state);
        userPageQueryRequest.setKeyword(keyWord);
        userPageQueryRequest.setCurrentPage(currentPage);
        userPageQueryRequest.setPageSize(pageSize);

        PageResponse<UserInfo> pageResponse = userFacadeService.pageQuery(userPageQueryRequest);

        return MultiResultConvertor.convert(pageResponse);
    }


    /**
     * 登录方法
     *
     * @param loginParam 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Result<AdminLoginVO> login(@Valid @RequestBody AdminLoginParam loginParam){

        //查询用户信息
        UserQueryRequest userQueryRequest = new UserQueryRequest(loginParam.getTelephone(),loginParam.getPassword());
        UserQueryResponse<UserInfo> userQueryResponse = userFacadeService.query(userQueryRequest);
        UserInfo userInfo = userQueryResponse.getData();
        //用户不存在（密码错误） 或者不是管理员，不能登录
        if (userInfo == null || !userInfo.getUserRole().equals(UserRole.ADMIN)){
            return Result.error(ADMIN_USER_NOT_EXIST.getCode(), ADMIN_USER_NOT_EXIST.getMessage());
        }else {
            //登录
            StpUtil.login(userInfo.getUserId(), new SaLoginModel().setIsLastingCookie(loginParam.getRememberMe()).setTimeout(DEFAULT_LOGIN_SESSION_TIMEOUT));
            StpUtil.getSession().set(userInfo.getUserId().toString(), userInfo);
            AdminLoginVO loginVO = new AdminLoginVO(userInfo);
            return Result.success(loginVO);
        }
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result<Boolean> logout(){
        StpUtil.logout();
        return Result.success(true);
    }

    /**
     * 冻结用户
     * @param userId 用户id
     * @return
     */
    @PostMapping("/freeze")
    public Result<UserOperatorResponse> freeze(@Valid Long userId){
        String adminUserId = (String)StpUtil.getLoginId();

        UserQueryRequest adminQueryRequest = new UserQueryRequest(adminUserId);
        UserQueryResponse<UserInfo> adminQueryResponse = userFacadeService.query(adminQueryRequest);

        UserInfo userInfo = adminQueryResponse.getData();
        //用户不存在，或者不是管理员用户
        if (userInfo == null || !userInfo.getUserRole().equals(UserRole.ADMIN)){
            return Result.error(ADMIN_USER_NOT_EXIST.getCode(), ADMIN_USER_NOT_EXIST.getMessage());
        }

        var res = userManageFacadeService.freeze(userId);

        //重新查出用户信息，更新登录的session,确保用户权限实时更新
        refreshUserInSession(userId);
        return Result.success(res);
    }

    /**
     * 解冻用户
     * @param userId 用户id
     * @return
     */
    @PostMapping("/unfreeze")
    public Result<UserOperatorResponse> unfreeze(@Valid Long  userId){
        String adminUserId = (String)StpUtil.getLoginId();
        //查询用户信息
        UserQueryRequest adminQueryRequest = new UserQueryRequest(userId);
        UserQueryResponse<UserInfo> adminQueryResponse = userFacadeService.query(adminQueryRequest);
        //获取到查询到的用户信息
        UserInfo userInfo = adminQueryResponse.getData();
        //用户不存在，或者不是管理员
        if (userInfo == null || userInfo.getUserRole().equals(UserRole.ADMIN)){
            return Result.error(ADMIN_USER_NOT_EXIST.getCode(),ADMIN_USER_NOT_EXIST.getMessage());
        }

        //解冻账户
        var res = userManageFacadeService.unfreeze(userId);

        //重新查出用户信息，更新登录的session,确保用户权限的实时更新
        refreshUserInSession(userId);
        return Result.success(res);
    }


    private void refreshUserInSession(Long userId){
        //创建一个用户请求对象
        UserQueryRequest userQueryRequest = new UserQueryRequest(userId);
        //远程调用query方法查询用户信息
        UserQueryResponse<UserInfo> userQueryResponse = userFacadeService.query(userQueryRequest);
        //将查询到的用户信息保存到sa-token中
        StpUtil.getSession().set(userId.toString(), userQueryResponse.getData());
    }
}
